package net.wicp.tams.commons.mq.ons;

import java.util.Properties;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.aliyun.openservices.ons.api.Consumer;
import com.aliyun.openservices.ons.api.MessageListener;
import com.aliyun.openservices.ons.api.ONSFactory;
import com.aliyun.openservices.ons.api.PropertyKeyConst;

import net.wicp.tams.commons.Conf;
import net.wicp.tams.commons.apiext.CollectionUtil;

public class AcceptMsOns {
	private final static Logger logger = LoggerFactory.getLogger(AcceptMsOns.class);

	/***
	 * 一般的注册监听事件
	 * 
	 * @param consumerId
	 *            消费者ID
	 * @param listener
	 *            监听者
	 * @param topic
	 *            消费主题
	 * @param tags
	 *            消费标签，不填为全部“*”
	 */
	public static Consumer RegistListener(String consumerId, MessageListener listener, String topic, String... tags) {
		if (StringUtils.isBlank(consumerId) || StringUtils.isBlank(topic) || listener == null) {
			logger.error("注册监听失败，缺少必要的参数");
			throw new IllegalArgumentException("需要consumerId、topic、listener");
		}
		Properties properties = new Properties();
		properties.put(PropertyKeyConst.ConsumerId, consumerId);
		properties.put(PropertyKeyConst.AccessKey, Conf.get("ons.server.accesskey"));
		properties.put(PropertyKeyConst.SecretKey, Conf.get("ons.server.secretkey"));
		properties.put(PropertyKeyConst.ONSAddr, Conf.get("ons.server.onsaddr"));
		Consumer consumer = ONSFactory.createConsumer(properties);
		String tagTrue = ArrayUtils.isEmpty(tags) ? "*" : CollectionUtil.arrayJoin(tags, "|");
		consumer.subscribe(topic, tagTrue, listener);
		consumer.start();
		logger.info("注册监听成功,consumerId：{}，topic：{}", consumerId, topic);
		return consumer;
	}

	/***
	 * 一般的注册监听事件
	 * 
	 * @param consumerId
	 *            消费者ID
	 * @param listener
	 *            监听者
	 * @param topic
	 *            消费主题
	 */
	public static Consumer RegistListener(String consumerId, MessageListener listener, String topic) {
		return RegistListener(consumerId, listener, topic, "*");
	}

}
